#include "I2C.h"

int I2C::begin()
{
    if (mode == I2C_Mode_Soft)
    {
        i2c_soft = i2c_soft_init(i2c_soft.SDA, i2c_soft.SCL, i2c_soft.delay_time);
    }
    else
    {
        i2c_hard = i2c_hard_init(i2c_hard.i2c, i2c_hard.speed);
    }
    return 1;
}

int I2C::end()
{
    return 1;
}

uint8_t I2C::getDeviceAddr()
{
    if (mode == I2C_Mode_Soft)
    {
        return i2c_soft.addr;
    }
    else
    {
        return i2c_hard.addr;
    }
}

uint8_t I2C::check()
{
    if (mode == I2C_Mode_Soft)
    {
        return i2c_soft_check(&i2c_soft);
    }
		else
		{
			return i2c_hard_check(&i2c_hard);
		}
}

void I2C::loadSlave(uint8_t addr)
{
    if (mode == I2C_Mode_Soft)
    {
        i2c_soft.addr = addr;
    }
    else
    {
        i2c_hard.addr = addr;
    }
}

void I2C::deloadSlave()
{
    if (mode == I2C_Mode_Soft)
    {
        i2c_soft.addr = NULL;
    }
    else
    {
        i2c_hard.addr = NULL;
    }
}

size_t I2C::write(uint8_t addr, uint8_t byte)
{
    if (mode == I2C_Mode_Soft)
    {
        return i2c_soft_reg_write_data(&i2c_soft, addr, byte);
    }
    else
    {
        return i2c_hard_reg_write_data(&i2c_hard, addr, byte);
    }
}

size_t I2C::write(uint8_t addr, const uint8_t *buf, size_t size)
{
    if (mode == I2C_Mode_Soft)
    {
        return i2c_soft_reg_write_datas(&i2c_soft, addr, buf, size);
    }
    else
    {
        return i2c_hard_reg_write_datas(&i2c_hard, addr, buf, size);
    }
}

size_t I2C::write(uint8_t addr, const uint8_t data, size_t size)
{
    if (mode == I2C_Mode_Soft)
    {
        return i2c_soft_reg_fill_datas(&i2c_soft, addr, data, size);
    }
    else
    {
        return i2c_hard_reg_fill_datas(&i2c_hard, addr, data, size);
    }
}

uint16_t I2C::read(uint8_t addr)
{
    if (mode == I2C_Mode_Soft)
    {
        return i2c_soft_reg_receive_data(&i2c_soft, addr);
    }
    else
    {
        return i2c_hard_reg_receive_data(&i2c_hard, addr);
    }
}

size_t I2C::read(uint8_t addr, uint8_t *buf, size_t size)
{
    if (mode == I2C_Mode_Soft)
    {
        for (int i = 0; i < size; i++)
        {
            buf[i] = i2c_soft_reg_receive_data(&i2c_soft, addr + i);
            if (buf[i] == 0xfe)
                return 0xfe;
        }
        return 1;
    }
    else
    {
        return i2c_hard_reg_receive_datas(&i2c_hard, addr, buf, size);
    }
}
